<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { insertHoliday } from '@/service/api/holiday';

interface Emits {
  (e: 'close'): void;
}

interface Props {
  open: boolean;
}

defineOptions({
  name: 'AddCurrencyModal'
});

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const loading = ref(false);

const formModel = reactive({
  currencyCode: '',
  holidayDate: '',
  dayType: 0, // 0-假日，1-调休工作日
  holidayNameEn: ''
});

const visible = computed({
  get() {
    return props.open;
  },
  set(value) {
    if (!value) {
      emit('close');
    }
  }
});

// 表单验证规则
const rules = {
  currencyCode: [
    { required: true, message: '请输入货币代码', trigger: 'blur' as const },
    { pattern: /^[A-Z]{3}$/, message: '货币代码必须是3位大写字母', trigger: 'blur' as const }
  ],
  holidayDate: [{ required: true, message: '请选择假日日期', trigger: 'change' as const }]
};

// 提交表单
async function handleSubmit() {
  loading.value = true;
  try {
    const { error } = await insertHoliday({
      currencyCode: formModel.currencyCode.toUpperCase(),
      holidayDate: formModel.holidayDate,
      dayType: formModel.dayType,
      holidayNameEn: formModel.holidayNameEn
    });

    if (!error) {
      window.$message?.success('新增货币假日成功');
      handleClose();
    } else {
      console.error('新增失败:', error);
    }
  } catch (error) {
    console.error('新增失败:', error);
  } finally {
    loading.value = false;
  }
}

// 关闭模态框
function handleClose() {
  visible.value = false;
  // 重置表单
  Object.assign(formModel, {
    currencyCode: '',
    holidayDate: '',
    dayType: 0,
    holidayNameEn: ''
  });
}
</script>

<template>
  <AModal v-model:open="visible" title="新增货币假日" width="500px" @cancel="handleClose">
    <template #footer>
      <AButton @click="handleClose">取消</AButton>
      <AButton type="primary" :loading="loading" @click="handleSubmit">确定</AButton>
    </template>

    <AForm :model="formModel" :rules="rules" layout="vertical">
      <AFormItem label="货币代码" name="currencyCode">
        <AInput
          v-model:value="formModel.currencyCode"
          placeholder="请输入3位货币代码，如：USD、CNY"
          :maxlength="3"
          style="text-transform: uppercase"
        />
      </AFormItem>

      <AFormItem label="假日日期" name="holidayDate">
        <ADatePicker v-model:value="formModel.holidayDate" placeholder="请选择假日日期" style="width: 100%" />
      </AFormItem>

      <AFormItem label="日期类型" name="dayType">
        <ARadioGroup v-model:value="formModel.dayType">
          <ARadio :value="0">假日</ARadio>
          <ARadio :value="1">调休工作日</ARadio>
        </ARadioGroup>
      </AFormItem>

      <AFormItem label="假日名称（英文）" name="holidayNameEn">
        <AInput v-model:value="formModel.holidayNameEn" placeholder="请输入假日名称（可选）" />
      </AFormItem>
    </AForm>
  </AModal>
</template>

<style scoped>
.ant-input {
  text-transform: uppercase;
}
</style>
